/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout from '@ant-design/pro-layout';
import { useEffect, useState } from 'react';
import Link from 'umi/link';
import { connect } from 'dva';
import { formatMessage } from 'umi-plugin-react/locale';
import { Menu, Row, Col, Button, Icon } from 'antd';
import RightContent from '@/components/GlobalHeader/RightContent';
// import { isAntDesignPro } from '@/utils/utils';
// import logo from '../assets/logo.svg';
import logo from '../../public/img/logo.png';
import { axhttp } from '@/shared/axhttp';
import { axurl } from '@/shared/axurl';
import styles from './BasicLayout.less'; //不能去掉
import { axconst } from '@/shared/axconst';
import { router } from 'umi';

const { SubMenu } = Menu;
const genMenus = (menus) => {
    return menus.map(i => {
        if (i.children) {
            return (
                <SubMenu
                    key={i.id}
                    title={
                        <span>
                            <Icon type={i.icon} />
                            {i.name}
                        </span>
                    }
                >
                    {genMenus(i.children)}
                </SubMenu>
            );
        }
        else {
            return (
                <Menu.Item key={i.id}>
                    <Icon type={i.icon} />
                    {i.name}
                </Menu.Item>
            );
        }
    });
}
const footerRender = name => (
    // if (!isAntDesignPro()) {
    //   return defaultDom;
    // }

    <>
        {/* {defaultDom} */}
        <div
            style={{
                padding: '0px 24px 24px',
                textAlign: 'center',
            }}
        >
            <div>Copyright ©2020 {name}</div>
            {/* <a href="https://www.netlify.com" target="_blank" rel="noopener noreferrer">
          <img
            src="https://www.netlify.com/img/global/badges/netlify-color-bg.svg"
            width="82px"
            alt="netlify logo"
          />
        </a> */}
        </div>
    </>
);
const BasicLayout = props => {
    const { dispatch, children, collapsed, settings, currentApp, clientWidth } = props;
    const [menuData, setMenuData] = useState([]);
    const [headerMenu, setHeaderMenu] = useState([]);
    const [defaultSelectedKeys, setDefaultSelectedKeys] = useState([]);
    const [collapseIcon, setCollapseIcon] = useState('menu-fold');
    const [openKeys, setOpenKeys] = useState([]);
    const [selectedKeys, setSelectedKeys] = useState([]);

    const handleClientWidth = () => {
        const { dispatch } = props;
        return dispatch({
            type: `global/readClientWidth`,
            params: {
                clientWidth: window.document.body.clientWidth,
            }
        });
    }

    useEffect(() => {
        return;
        if (clientWidth !== 0 && clientWidth < 1400) {
            handleMenuCollapse(true);
        }
    }, [clientWidth])

    useEffect(() => {
        // return;
        // const menu = localStorage.getItem('ax-data-menu');
        const menu = `[
            {
                "url": "/",
                "permissions": 0,
                "menuVisitType": 0,
                "menuModule": 1,
                "text": "首页",
                "iconCls": "iconfont icon-setting-b",
                "expanded": false,
                "sortNum": 11,
                "leaf": false,
                "deep": 0,
                "id": "10",
                "created": "0001-01-01 00:00:00",
                "modified": "0001-01-01 00:00:00",
                "state": 0
            }
        ]`;
        let data = [];
        if (menu && menu !== 'null') {
            data = JSON.parse(menu);
        } else {
            // async function fetchData() {
            //   await axhttp.get(axurl.resource.menu).then(res => {
            //     if (res && res.success === true) {
            //       data = res.data;
            //     }
            //   });
            // }
            async function fetchData() {
                await axhttp.get('/api/servermenus').then(res => {
                    if (res && res.success === true) {
                        data = res.data;
                    }
                });
            }
            fetchData();
            if (data && data.length > 0) {
                localStorage.setItem('ax-data-menu', JSON.stringify(data));
            }
        }

        const transformData = [];
        if (data && data.length > 0) {
            data.forEach(i => {
                transformData.push(transFormMenus(i));
            });
            setHeaderMenu(transformData);

            if (transformData.length > 0) {
                let { hash } = location;
                if (hash.length > 0) {
                    hash = hash.substring(1);
                }
                let find = transformData.find(i => {
                    /** 精确匹配 */
                    const h = /\/(\S+?)\//.exec(hash);
                    if (h && h.length > 0 && i.path + '/' === h[0]) return true;
                    return false;
                });
                /** 模糊匹配 */
                if (find === undefined) find = transformData.find(i => hash.indexOf(i.path) !== -1);
                if (find) {
                    // setMenuData(find.children || []);
                    setMenuData([find]);
                    setDefaultSelectedKeys([find.id]);
                } else {
                    // setMenuData(transformData[0].children || []);
                    setMenuData([transformData[0]]);
                    setDefaultSelectedKeys([transformData[0].id]);
                }
            }
        }

        handleClientWidth();
        window.onresize = handleClientWidth;
    }, []);

    /** 转换菜单格式 */
    const transFormMenus = menu => {
        let obj = {};
        if (menu.children && menu.children.length > 0) {
            const menuChildren = [];
            menu.children.forEach(i => {
                menuChildren.push(transFormMenus(i));
            });
            obj = {
                id: menu.id,
                // key: menu.id,    //这里不能用key，默认将url作为了key，否则菜单展示会有问题
                path: menu.url,
                name: menu.text,
                icon: menu.iconCls,
                // icon: (menu.deep === 1 || menu.deep === 2) ? menu.iconCls : undefined,
                // hideInMenu: true,  //不展示改菜单
                // hideChildrenInMenu: true,  //不展示改菜单的子菜单
                // authority: ['admin', 'user'], //代表该路由的准入权限
                children: menuChildren,
                permissions: menu.permissions,
            };
        } else {
            obj = {
                id: menu.id,
                // key: menu.id,
                path: menu.url,
                name: menu.text,
                icon: menu.iconCls,
                // icon: (menu.deep === 1 || menu.deep === 2) ? menu.iconCls : undefined,
                permissions: menu.permissions,
                // hideInMenu: true,  //不展示改菜单
                // hideChildrenInMenu: true,  //不展示改菜单的子菜单
                // icon: menu.iconCls
            };
        }
        return obj;
    };

    /** 菜单折叠操作函数 */
    const handleMenuCollapse = payload => {
        setCollapseIcon(payload === false ? 'menu-fold' : 'menu-unfold');
        if (dispatch) {
            dispatch({
                type: 'global/changeLayoutCollapsed',
                payload,
            });
        }
    };

    /** 顶部菜单点击操作函数 */
    const handleHeaderMenu = ({ key }) => {
        if (headerMenu) {
            const menu = headerMenu.find(i => i.id === key);
            menu && router.push(menu.path);
        }
    };

    return (
        <ProLayout
            contentStyle={{ margin: 0 }}
            // 是否渲染菜单
            // menuRender={false}
            // logo={logo}
            // menuHeaderRender={(logoDom, titleDom) => (
            //   <Link to="/">
            //     {logoDom}
            //     {/* <Icon type="desktop" style={{ fontSize: '28px' }} /> */}
            //     {titleDom}
            //   </Link>
            // )}
            // logo={<Icon type="desktop" style={{ fontSize: '28px' }} />}
            collapsed={collapsed}
            onCollapse={() => collapsed}
            menuItemRender={(menuItemProps, defaultDom) => {
                debugger
                if (menuItemProps.isUrl) {
                    return defaultDom;
                }
                return (
                    <Link to={menuItemProps.path} replace>
                        {defaultDom}
                    </Link>
                );
            }}
            breadcrumbRender={(routers = []) => [
                {
                    path: '/',
                    breadcrumbName: formatMessage({
                        id: 'menu.home',
                        defaultMessage: 'Home',
                    }),
                },
                ...routers,
            ]}
            itemRender={(route, params, routes, paths) => {
                const first = routes.indexOf(route) === 0;
                return first ? (
                    <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
                ) : (
                        <span>{route.breadcrumbName}</span>
                    );
            }}
            headerRender={() => (
                <Row>
                    <Col span={6}>
                        <a style={{ paddingLeft: 16 }}>
                            <img src="/img/logo.png" style={{ height: 44, marginBottom: 2 }} />
                        </a>
                    </Col>
                    <Col span={16}>
                        <Menu
                            theme="light"
                            mode="horizontal"
                            selectedKeys={defaultSelectedKeys}
                            style={{ lineHeight: `${axconst.header.height - 2}px`, float: 'right', backgroundColor: '#409eff' }}
                            onClick={({ key }) => handleHeaderMenu({ key })}
                        // onClick={({ path }) => router.push('/')}
                        >
                            {menuData && menuData.length > 0 && genMenus(menuData) || <></>}
                        </Menu>
                    </Col>
                    <Col
                        span={2}
                        // className="ant-menu-dark"
                        style={{ height: 48 }}
                    >
                        <RightContent></RightContent>
                    </Col>
                </Row>
            )}
            footerRender={() => footerRender(currentApp.orgName)}
            menuDataRender={() => menuData}
            {...props}
            {...settings}
            title={currentApp.appName}
        >
            {children}
        </ProLayout>
    );
};

export default connect(({ global, settings, user }) => ({
    collapsed: global.collapsed,
    clientWidth: global.clientWidth,
    settings,
    currentApp: user.currentApp,
}))(BasicLayout);
